import {
  addExamQuestionBank,
  delExamQuestionBank,
  getExamQuestionBank,
  listExamQuestionBank,
  updateExamQuestionBank
} from "@/api/train/base/ExamQuestionBank.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listExamSubjectKnowledgePoints} from "@/api/train/base/ExamSubjectKnowledgePoints";
import {listPost} from '@/api/system/post.js'
import {
  Choice_Question_Option,
  JUDGE_QUESTION_RIGHT_KEY,
  KNOWLEDGE_POINTS_TYPE,
  QUESTION_TYPE
} from '@/views/train/Enums'
import {listDept} from '@/api/system/dept'
import {getToken} from "@/utils/auth";
import {SEPARATOR} from "@/utils/Constant";
import mixins from "@/views/train/mixins";

export default {
  components: {
    Treeselect
  },
  dicts: ['syllabus', 'post_level'],
  name: "ExamQuestionBank",
  mixins: [mixins],
  data() {
    return {
      treeData: [],
      knowledgePointsTree: [],
      treeProps: {
        label: 'name'
      },
      // 知识点的左侧树类型
      treeNodeType: {
        // 顶部节点
        HEADER: 0,
        // 岗位
        POST: 1,
        // 科目
        SUBJECT: 2,
        // 知识点
        KNOWLEDGE_POINTS: 3
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题库管理表格数据
      ExamQuestionBankList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        deptId: null,
        syllabusCode: null,
        postId: null,
        subjectId: null,
        knowledgePointsId: null,
        questionType: null,
        content: null,
        rightKey: null,
        postLevelCode: null,
        analysis: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          {required: true, message: "考题编码不能为空", trigger: "blur"}
        ],
        deptId: [
          {required: true, message: "部门不能为空", trigger: "blur"}
        ],
        syllabusCode: [
          {required: true, message: "大纲不能为空", trigger: "blur"}
        ],
        knowledgePointsId: [
          {required: true, message: "知识点不能为空", trigger: "blur"}
        ],
        questionType: [
          {required: true, message: "考题类型不能为空", trigger: "change"}
        ],
        content: [
          {required: true, message: "题干内容不能为空", trigger: "blur"}
        ],
        rightKey: [
          {required: true, message: "正确答案不能为空", trigger: "blur"}
        ],
        postLevelCode: [
          {required: true, message: "能力级别不能为空", trigger: "blur"}
        ],
      },
      options: {
        KNOWLEDGE_POINTS_TYPE: KNOWLEDGE_POINTS_TYPE,
        QUESTION_TYPE: QUESTION_TYPE,
        JUDGE_QUESTION_RIGHT_KEY: JUDGE_QUESTION_RIGHT_KEY,
        deptMap: {},
        postMap: {},
        examSubjectKnowledgePointsMap: {},
        Choice_Question_Option: Choice_Question_Option
      },
      // 当前树节点
      currentTreeNode: {},
      // 上传
      upload: {
        title: '',
        open: false,
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        url: process.env.VUE_APP_BASE_API + "/base/ExamQuestionBank/importData"
      },
    };
  },
  methods: {
    // 添加选项
    handleAddOption(index) {
      if (this.form.examQuestionBankOptionList.length < this.options.Choice_Question_Option.list.length) {
        this.form.examQuestionBankOptionList.splice(index + 1, 0, this.examQuestionBankOptionBuilder())
      }
    },
    // 删除选项
    handleRemoveOption(index) {
      if (this.form.examQuestionBankOptionList.length > 1) {
        this.form.examQuestionBankOptionList.splice(index, 1)
      } else {
        this.$message.warning('请至少保留一项')
      }
    },
    handleKnowledgePointsChange(value) {
      if (value.length !== 3) {
        this.$message.warning('请选择知识点层级!')
        this.form.knowledgePointsId = []
      }
    },
    handleQuestionTypeChange(){
      if(this.form.questionType === this.options.QUESTION_TYPE.enums.ChoiceQuestion.value){
        this.form.rightKey = []
      }else{
        this.form.rightKey = ''
      }
    },
    /**
     * 获取部门
     */
    getDept() {
      listDept().then(res => {
        this.options.deptList = res.data
        res.data.forEach(e => {
          this.options.deptMap[e.deptId] = e.deptName
        })
      })
    },
    /**
     * 获取左侧树
     */
    getTree() {
      // 获取科目+知识点,获取岗位
      Promise.all([listExamSubjectKnowledgePoints(), listPost()]).then(([pointRes, postRes]) => {
        let points = pointRes.rows || [], posts = postRes.rows || []

        points.forEach(e => {
          this.options.examSubjectKnowledgePointsMap[e.id] = e.name
        })
        posts.forEach(e => {
          this.options.postMap[e.postId] = e.postName
        })

        // 首先添加统一的类型,用于区分其类别
        posts.forEach(post => {
          post.queryType = this.treeNodeType.POST
        })
        points.forEach(point => {
          if (point.type === KNOWLEDGE_POINTS_TYPE.enums.SUBJECT.value) {
            point.queryType = this.treeNodeType.SUBJECT
          } else if (point.type === KNOWLEDGE_POINTS_TYPE.enums.KNOWLEDGE_POINTS.value) {
            point.queryType = this.treeNodeType.KNOWLEDGE_POINTS
          }
          point.parentId = point.subjectId
        })

        // 构建成树
        let treeData = this.handleTree(points)
        posts.forEach(post => {
          post.children = []
          post.name = post.postName
          post.id = post.postId
          treeData.forEach(tree => {
            if (tree.postId === post.postId) {
              post.children.push(tree)
            }
          })
        })
        this.treeData = [{id: '0', name: '题库', children: posts, queryType: this.treeNodeType.HEADER}]
        this.knowledgePointsTree = posts
      })
    },
    // 左侧树点击逻辑
    handleNodeClick(data) {
      this.currentTreeNode = data
      this.getList()
    },
    /** 查询题库管理列表 */
    getList() {
      this.loading = true;
      let params = {}

      switch (this.currentTreeNode.queryType) {
        case this.treeNodeType.POST:
          params.postId = this.currentTreeNode.postId
          break
        case this.treeNodeType.SUBJECT:
          params.subjectId = this.currentTreeNode.id
          break
        case this.treeNodeType.KNOWLEDGE_POINTS:
          params.knowledgePointsId = this.currentTreeNode.id
      }
      listExamQuestionBank(this.doSort({...this.queryParams, ...params}, 'createTime')).then(response => {
        this.ExamQuestionBankList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        deptId: null,
        syllabusCode: null,
        knowledgePointsId: [],
        questionType: null,
        content: null,
        rightKey: null,
        postLevelCode: null,
        analysis: null,
        remark: null,
        examQuestionBankOptionList: [this.examQuestionBankOptionBuilder()]
      };
      this.resetForm("form");
      this.currentTreeNode = {}
    },
    addOption() {
      this.form.examQuestionBankOptionList.push(this.examQuestionBankOptionBuilder())
    },
    examQuestionBankOptionBuilder() {
      return ''
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题库管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getExamQuestionBank(id).then(response => {
        let data = JSON.parse(JSON.stringify(response.data))
        this.dataConvert(data)
        this.form = data;
        this.open = true;
        this.title = "修改题库管理";
      });
    },
    // 数据整合,用于回传给后端
    dataParse(data) {
      if (~[this.options.QUESTION_TYPE.enums.ChoiceQuestion.value, this.options.QUESTION_TYPE.enums.FillBlankQuestionExcel.value].indexOf(data.questionType)) {
        if (Array.isArray(data.examQuestionBankOptionList) && data.examQuestionBankOptionList.length) {
          let options = []
          data.examQuestionBankOptionList.forEach((e, index) => {
            options.push({
              content: e,
              sort: index,
            })
          })
          data.examQuestionBankOptionList = options
        } else {
          this.$message.warning('选项不能为空')
          throw new Error('选项不能为空')
        }
      } else {
        delete (data.examQuestionBankOptionList)
      }
      if (this.options.QUESTION_TYPE.enums.FillBlankQuestionExcel.value === data.questionType) {
        data.rightKey = data.examQuestionBankOptionList.map(e => e.content).join(SEPARATOR)
      }
      if (this.options.QUESTION_TYPE.enums.ChoiceQuestion.value === data.questionType) {
        data.rightKey = data.rightKey.join(',')
      }

      data.postId = data.knowledgePointsId[0]
      data.subjectId = data.knowledgePointsId[1]
      data.knowledgePointsId = data.knowledgePointsId[2]
    },
    // 数据整理,用于整合到前端
    dataConvert(data) {
      if (~[this.options.QUESTION_TYPE.enums.ChoiceQuestion.value, this.options.QUESTION_TYPE.enums.FillBlankQuestionExcel.value].indexOf(data.questionType)) {
        if (Array.isArray(data.examQuestionBankOptionList) && data.examQuestionBankOptionList.length) {
          let options = []
          data.examQuestionBankOptionList.sort((e1, e2) => e1.sort - e2.sort)
          data.examQuestionBankOptionList.forEach((e, index) => {
            options.push(e.content)
          })
          data.examQuestionBankOptionList = options
        } else {
          this.$message.warning('选项为空,请重新维护')
          data.examQuestionBankOptionList = ['']
        }
      } else {
        // delete (this.form.examQuestionBankOptionList)
        data.examQuestionBankOptionList = ['']
      }
      data.knowledgePointsId = [data.postId, data.subjectId, data.knowledgePointsId]
      if(data.questionType === this.options.QUESTION_TYPE.enums.ChoiceQuestion.value){
        if(data.rightKey){
          data.rightKey = data.rightKey.split(',')
        }else{
          data.rightKey = []
        }
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.form))
          this.dataParse(data)
          if (this.form.id != null) {
            updateExamQuestionBank(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExamQuestionBank(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('确认删除？').then(function () {
        return delExamQuestionBank(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/ExamQuestionBank/export', {
        ...this.queryParams
      }, `ExamQuestionBank_${new Date().getTime()}.xlsx`)
    },
    // 导入
    handleImport() {
      this.upload.title = "考题导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    handleFileError() {
      this.$message.error('导入失败')
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    init() {
      this.getTree()
      this.getList()
      this.getDept()
    }
  },
  created() {
    this.init()
  },
};
